from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_categories():
    # 0.初始化数据
    categories = OrderedDict()
    # 1.查询频道数据
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 2.遍历
    for channel in channels:
        # 3.组织频道数据结构
        group_id = channel.group_id  # 获取当前频道
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        # 4.获取当前频道的分类
        cat1 = channel.category

        # 5.追加当前频道
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })

        # 6.组织当前类别的子类
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            # 追加数据
            categories[group_id]['sub_cats'].append(cat2)

    return categories